package com.demo.springSecurityJwt.service.impl;

import com.demo.springSecurityJwt.model.BlueDashBoard;
import com.demo.springSecurityJwt.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Hanson
 * @date 2022/9/13 14:57
 */
@Slf4j
@Service
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;	//Spring自动注入RedisTemplate

    @Override
    public void addKey(String key, String value) {
        // 20: 表示该数据在缓存中存在的时间，TimeUnit.SECONDS为单位秒，
        // 20秒后缓存中的数据会自动消失
        redisTemplate.opsForValue().set(key,value,20, TimeUnit.SECONDS);
    }

    @Override
    public String getValueByKey(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * @return 获取redis中缓存的数据
     */
    @Override
    public BlueDashBoard getDashBoard() {
        BlueDashBoard dash = new BlueDashBoard();
        dash.setReceptionTotalByDay(Long.parseLong(
                Objects.requireNonNull(
                        redisTemplate.opsForValue().get("stream:board:reception:day")
                ).toString()));
        dash.setReceptionTotalByMon(Long.parseLong(
                Objects.requireNonNull(
                        redisTemplate.opsForValue().get("stream:board:reception:month")
                ).toString()));
        dash.setReceptionTotalByYear(Long.parseLong(
                Objects.requireNonNull(
                        redisTemplate.opsForValue().get("stream:board:reception:year")
                ).toString()));
        Long receptionTotalByDay = dash.getReceptionTotalByDay();
        Long receptionTotalByMon = dash.getReceptionTotalByMon();
        Long receptionTotalByYear = dash.getReceptionTotalByYear();
        log.info("日接入：{}，月接入：{}，年接入：{}",receptionTotalByDay,receptionTotalByMon,receptionTotalByYear);
        return dash;
    }
}

